package io.vertx.kue.example

import io.vertx.kue.Kue
import io.vertx.kue.queue.*
import io.vertx.core.AbstractVerticle
import io.vertx.core.Handler
import io.vertx.core.json.JsonObject


/**
 * Vert.x Blueprint - Job Queue
 * Example - A learning Vert.x process verticle!
 * This example shows the job events
 *
 * @author Eric Zhao
 */
class LearningVertxVerticle : AbstractVerticle() {

    @Throws(Exception::class)
    override fun start() {
        // create our job queue
        val kue = Kue.createQueue(vertx, config())

        // consume queue error
        kue.on<Any>("error", Handler{ message -> println("[Global Error] " + message.body()) })

        val data = JsonObject()
                .put("title", "Learning Vert.x")
                .put("content", "core")

        // we are going to learn Vert.x, so create a job!
        val j = kue.createJob("learn vertx", data)
                .priority(Priority.HIGH)
                .onComplete(Handler{ // on complete handler
                    r ->
                    println("Feeling: " + r.getResult()!!.getString("feeling", "none"))
                }).onFailure(Handler{ // on failure handler
            r ->
            println("eee...so difficult...")
        }).onProgress(Handler{ // on progress modifying handler
            r ->
            println("I love this! My progress => " + r!!)
        })

        // save the job
        j.save().setHandler { r0 ->
            if (r0.succeeded()) {
                // start learning!
                kue.processBlocking("learn vertx", 1, Handler{ job ->
                    job.progress(10, 100)
                    // aha...spend 3 seconds to learn!
                    vertx.setTimer(3000) { r1 ->
                        job.setResult(JsonObject().put("feeling", "amazing and wonderful!")) // set a result to the job
                                .done() // finish learning!
                    }
                })
            } else {
                System.err.println("Wow, something happened: " + r0.cause().message)
            }
        }
    }

}
